package com.jasic.comnt.protocol.bean;

import com.jasic.common.GlobalConstant;
import com.jasic.common.exception.HandleException;
import com.jasic.comnt.protocol.MessageCommon;
import com.jasic.util.Asserter;
import com.jasic.util.ByteUtil;
import com.jasic.util.ProtocolUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * User: Jasic
 * Date: 12-12-22
 */
public class Login extends BaseRequest {

    private static Logger logger = LoggerFactory.getLogger(Login.class);

    /**
     * This must be look as number combined
     */
    private String userName;

    private String password;

    public Login(String userName, String password) {

        super(new MessageCommon(GlobalConstant.ADD_CONNTDN_0x7e, GlobalConstant.LOGIN_LENGTH, GlobalConstant.CMD_LOGIN, GlobalConstant.BUSINESS_SERVER, GlobalConstant.PROTOCOL_SERVER, GlobalConstant.ADD_CONNTDN_0x7e));
        this.userName = userName;
        this.password = password;

        super.initCheckNum();
    }

    public Login(byte[] data) throws HandleException {
        super(data);
    }

    @Override
    public byte[] getMsgByte() {
        Asserter.isTrue(ProtocolUtil.validateFormat(userName, password), "The userName or password can't to be formatted...");
        int userNameLen = userName.length();

        StringBuilder sb = new StringBuilder();
        // 当字符串 ‘12’ -->转成bcd，0x12时长度减半
        for (int i = 0; i < GlobalConstant.LOGIN_USERNAME_LENGTH * 2 - userNameLen; i++) {
            sb.append("0");
        }
//        logger.info("--------------userName HEX:");
        byte[] bcdUserName = ByteUtil.stringToBCD(sb.toString() + userName);
        for (byte b : bcdUserName) {
//            logger.info(b+"");
        }

//        logger.info("--------------password:HEX");
        byte pswBytes[] = password.getBytes();
        for (byte b : pswBytes) {
//            logger.info(b+"");
        }

        byte msg[] = new byte[bcdUserName.length + pswBytes.length];
        System.arraycopy(bcdUserName, 0, msg, 0, bcdUserName.length);
        System.arraycopy(pswBytes, 0, msg, bcdUserName.length, pswBytes.length);
        return msg;
    }

    @Override
    protected void setValues() {
        // 因为用名户高位填0的缘故，不能从byte转到String，因为不能确定真实userName所占的byte[]的长度
    }

    public String getUserName() {
        return userName;
    }

    public String getPassword() {
        return password;
    }
}
